package com.pig4cloud.pig.ads.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pig4cloud.pig.ads.service.AdvService;
import com.pig4cloud.pig.ads.service.TlpService;
import com.pig4cloud.pig.ads.service.TtAccesstokenService;
import com.pig4cloud.pig.ads.utils.OEHttpUtils;
import com.pig4cloud.pig.api.entity.ResponseBean;
import com.pig4cloud.pig.api.entity.ThirdLandingPage;
import com.pig4cloud.pig.ads.pig.mapper.TlpMapper;
import com.pig4cloud.pig.common.core.constant.enums.PlatformTypeEnum;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.security.util.SecurityUtils;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @落地页 服务实现类
 * @author yk
 */
@Service
@RequiredArgsConstructor
public class TlpServiceImpl extends ServiceImpl<TlpMapper, ThirdLandingPage> implements TlpService {

	@Autowired
	private TlpMapper tlpMapper;

	@Autowired
	private final TtAccesstokenService ttAccesstokenService;

	@Autowired
	private AdvService advService;

	//修改落地页名称
	@Override
	public R updateSelective(ThirdLandingPage req) {
		String pageName = req.getPageName();
		if (StringUtils.isBlank(pageName)) {
			return R.failed("落地页名称不能为空");
		}
		if (pageName.length() > 50) {
			return R.failed("落地页名称长度不超过50字，请正确输入");
		}
		if (!nameMatches(pageName)) {
			return R.failed("落地页名称仅支持字母、数字、下划线、中文");
		}
		int id = req.getId();
		ThirdLandingPage tlp = tlpMapper.selectById(id);
		String advertiserId = tlp.getAdvertiserId();
		String pageId = tlp.getPageId();
		//调第三方平台（头条）接口，同步修改第三方落地页
		String thirdSiteUpdateUrl = "https://ad.oceanengine.com/open_api/2/tools/third_site/update/";
		Map<String, Object> data = new HashMap<String, Object>();
		data.put("advertiser_id", advertiserId);
		data.put("name", pageName);
		data.put("site_id", pageId);
		String accessToken = ttAccesstokenService.fetchAccesstoken(advertiserId);
		String resultString= OEHttpUtils.doPost(thirdSiteUpdateUrl, data, accessToken);
		ResponseBean responseBean = JSON.parseObject(resultString, ResponseBean.class);
		String siteId = null;
		if (responseBean != null && "0".equals(responseBean.getCode())) {
			JSONObject jsonObj = responseBean.getData();
			siteId = jsonObj.getString("site_id");
		}
		if (StringUtils.isBlank(siteId)){
			return R.failed("获取站点id失败");
		}
		if(!siteId.equals(pageId)){
			return R.failed("投放平台与头条站点id不匹配");
		}
		int i = tlpMapper.updateByPrimaryKeySelective(req);
		return R.ok(i, "落地页名称修改成功");
	}

	//添加落地页
	@Override
	public R create(ThirdLandingPage tlp) {
		//获取到当前登录用户
		Integer id = SecurityUtils.getUser().getId();
		//获取当前账号下 广告账户列表
		List<String> allList = advService.getOwnerAdv(id, PlatformTypeEnum.TT.getValue());
		if(allList == null || allList.size() == 0) {
			return R.failed("当前用户下没有广告账户");
		}
		//判断集合中是否包含广告主id
		String advertiserId = tlp.getAdvertiserId();
		if(StringUtils.isBlank(advertiserId)){
			return R.failed("广告账户不能为空");
		}
		if(!allList.contains(advertiserId)) {
			return R.failed("广告账户不可用");
		}
		String pageName = tlp.getPageName();
		String url = tlp.getUrl();
		if (StringUtils.isBlank(pageName) || StringUtils.isBlank(url)){
			return R.failed("落地页名称、落地页链接不能为空");
		}
		if (pageName.length() > 50) {
			return R.failed("落地页名称长度不超过50字，请正确输入");
		}
		if (!nameMatches(pageName)) {
			return R.failed("落地页名称仅支持字母、数字、下划线、中文");
		}
		if (!isURL(url)) {
			return R.failed("落地页链接无法访问，请正确输入");
		}
		//判断站点URL是否存在
		QueryWrapper<ThirdLandingPage> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("url", url);
		ThirdLandingPage record = tlpMapper.selectOne(queryWrapper);
		if (Objects.nonNull(record)) {
			return R.failed("落地页链接已存在");
		}
		//调第三方平台（头条）接口，同步创建第三方落地页，获取站点id
		String thirdSiteCreateUrl = "https://ad.oceanengine.com/open_api/2/tools/third_site/create/";
		Map<String, Object> data1 = new HashMap<String, Object>();
		data1.put("advertiser_id", advertiserId);
		data1.put("name", pageName);
		data1.put("url", url);
		String accessToken = ttAccesstokenService.fetchAccesstoken(advertiserId);
		String resultString= OEHttpUtils.doPost(thirdSiteCreateUrl, data1, accessToken);
		ResponseBean responseBean = JSON.parseObject(resultString, ResponseBean.class);
		String siteId = null;
		if (responseBean != null && "0".equals(responseBean.getCode())) {
			JSONObject jsonObj = responseBean.getData();
			siteId = jsonObj.getString("site_id");
		}
		if(StringUtils.isBlank(siteId)){
			return R.failed("获取站点id失败");
		}
		//调第三方平台（头条）接口，获取站点详情
		String thirdSiteGetUrl = "https://ad.oceanengine.com/open_api/2/tools/third_site/get/";
		Map<String, Object> data = new HashMap<String, Object>();
		Map<String, Object> filter = new HashMap<>();
		filter.put("site_id", siteId);
		data.put("advertiser_id", advertiserId);
		data.put("page", "1");//页码. 默认值: 1
		data.put("page_size", "10");//页面数据量. 默认值: 10
		data.put("filtering", filter);
		String resultStr = OEHttpUtils.doGet(thirdSiteGetUrl, data, accessToken);
		ResponseBean resBean = JSON.parseObject(resultStr, ResponseBean.class);
		JSONArray array = null;
		if (resBean != null && "0".equals(resBean.getCode())) {
			JSONObject jsonObj = resBean.getData();
			array = jsonObj.getJSONArray("list");
		}
		JSONObject obj = (JSONObject) array.get(0);
		boolean eq = siteId.equals(obj.getString("site_id"));
		if(array.size() !=1 || (!eq)){
			return R.failed("获取站点详情失败");
		}
			tlp.setPageUrl(obj.getString("thumbnail"));
			tlp.setPageName(obj.getString("name"));
			tlp.setPageId(siteId);
			tlp.setAuditStatus(obj.getString("audit_status"));
			tlp.setCreateUser(id+"");
			try {
				tlp.setCreateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(obj.getString("create_time")));
			} catch (ParseException e) {
				e.printStackTrace();
			}
			tlp.setUrl(obj.getString("url"));
			tlp.setAdvertiserId(advertiserId);
			int i = tlpMapper.insertSelective(tlp);
			return R.ok(i, "添加成功");
	}

	//落地页名称仅支持字母、数字、下划线、中文
	public boolean nameMatches(String str) {
		String regex ="^[a-zA-Z0-9_\u4e00-\u9fa5]+$";
		return str.matches(regex);
	}

	/**
	 * 判断一个字符串是否为url
	 * @param str String 字符串
	 * @return boolean 是否为url
	 **/
	public boolean isURL(String str) {
		//转换为小写
		str = str.toLowerCase();
		String regex = "^((https|http|ftp|rtsp|mms)?://)"  //https、http、ftp、rtsp、mms
				+ "?(([0-9a-z_!~*'().&=+$%-]+: )?[0-9a-z_!~*'().&=+$%-]+@)?" //ftp的user@
				+ "(([0-9]{1,3}\\.){3}[0-9]{1,3}" // IP形式的URL- 例如：199.194.52.184
				+ "|" // 允许IP和DOMAIN（域名）
				+ "([0-9a-z_!~*'()-]+\\.)*" // 域名- www.
				+ "([0-9a-z][0-9a-z-]{0,61})?[0-9a-z]\\." // 二级域名
				+ "[a-z]{2,6})" // first level domain- .com or .museum
				+ "(:[0-9]{1,5})?" // 端口号最大为65535,5位数
				+ "((/?)|" // a slash isn't required if there is no file name
				+ "(/[0-9a-z_!~*'().;?:@&=+$,%#-]+)+/?)$";
		return str.matches(regex);
	}
}
